import 'dart:convert';
import 'dart:typed_data';

import 'package:crypto/crypto.dart';
import 'package:dio/dio.dart';
import 'package:encrypt/encrypt.dart';
import 'package:xvideos/assets_tool/lang.dart';
import 'package:xvideos/config/address.dart';
import 'package:xvideos/config/config.dart';
import 'package:xvideos/hj_utils/global.dart';
import 'package:xvideos/hj_utils/http_manager.dart';
import 'package:xvideos/hj_utils/light_model.dart';
import 'package:xvideos/tools_base/debug_log.dart';
import 'package:xvideos/tools_base/net/base_resp_bean.dart';
import 'package:xvideos/tools_base/net/code.dart';
import 'package:xvideos/tools_base/net/curl_util.dart';

/// curl 工具

class HttpResponseInterceptor extends InterceptorsWrapper {
  static const String TAG = "HttpRespInterceptor";

  HttpResponseInterceptor();
  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    // super.onResponse(response, handler);
    final curl = CurlUtil.generateCurl(response.requestOptions);
    debugLog('HttpResponseInterceptor curl ====== $curl');
    debugLog('==========response==========');
    debugLog('${response.data}');
    handleResponse(response);
    handler.next(response);
  }

  @override
  void onError(
    DioException err,
    ErrorInterceptorHandler handler,
  ) {
    // debugLog('onError: ${err.requestOptions.path} ');
    // debugLog('onError: ${err.requestOptions.queryParameters}');
    // debugLog('onError: ${err.requestOptions.data}');
    // debugLog('onError: ${err.requestOptions.headers}');
    // debugLog('err:${err.error}');
    final curl = CurlUtil.generateCurl(err.requestOptions);
    debugLog('HttpResponseInterceptor curl ====== $curl');

    handler.next(err);
  }

  handleResponse(Response response) {
    // if (response.statusCode != 200) {
    //   throw Future.error(ApiException(response.statusCode, response.statusMessage));
    // }

    BaseRespBean baseResp;
    if (response.statusCode != 200) {
      baseResp = BaseRespBean(response.statusCode, msg: response.statusMessage);
    } else {
      if (response.data is Map) {
        if (Address.ALI_CCD_API.contains(response.realUri.path)) {
          baseResp = BaseRespBean(200, data: response.data);
        } else
          baseResp = BaseRespBean.fromJson(response.data);
      } else if (response.data is String) {
        try {
          baseResp = BaseRespBean.fromJson(json.decode(response.data));
        } catch (e) {
          baseResp = BaseRespBean(Code.PARSE_DATE_ERROR, msg: Lang.PARSE_DATE_ERROR);
        }
      } else if (response.data is BaseRespBean) {
        baseResp = response.data;
      } else {
        baseResp = BaseRespBean(Code.PARSE_DATE_ERROR, msg: Lang.PARSE_DATE_ERROR);
      }
      // 同步下服务器时间
      httpManager.setServerTime(baseResp.time);
      final code = baseResp.code;
      if (code == Code.SUCCESS) {
        dynamic data = baseResp.data;
        // 加密的数据
        if (baseResp.hash ?? false) {
          final decryptData = aesDecryptEx(data ?? '', Config.encryptKey);
          data = json.decode(decryptData);
          debugLog('解密后 data === $data');
        }
        baseResp.printData = data;
        baseResp.data = data;
      } else if (code == Code.FORCE_UPDATE_VERSION) {
        //需要更新
        baseResp.msg = "您的版本需要更新了";
        // await handleVer(baseResp.data);
      } else if (code == Code.ACCOUNT_INVISIBLE) {
        //账户被封禁了
        baseResp.msg = "您的账号已被封禁了";
        dynamic data = baseResp.data;
        if (baseResp.hash ?? false) {
          final decryptData = aesDecryptEx(data, Config.encryptKey);
          data = json.decode(decryptData);
        }
        baseResp.data = data;
      } else if (code == Code.TOKEN_ABNORMAL) {
        //token异常
        baseResp.msg = "token异常";
        // 清理token过期后 重新登陆问题
        lightKV.setString("_key_net_token", '');
        // if (!VariableConfig.onMobileLoginView) {
        //   DialogGlobal.instance.openTakenAbnormalDialog();
        // }
      } else if (code == Code.VERIFY_CODE_REPEAT) {
        //验证码频繁异常
        baseResp.msg = "获取验证码过于频繁";
      } else {
        //pk打榜单独处理
        if (!response.realUri.path.contains('/pkgame/vote')) baseResp.data = null;
      }
    }
    if (!baseResp.isSuccess) showToast(baseResp.toast);
    response.data = baseResp;
  }

  // 数据解密
  String aesDecryptEx(String cipher, String key) {
    // final t1 = DateTime.now();
    const nonceLen = 12;
    final cipherBytes = base64Decode(cipher);
    final nonce = cipherBytes.sublist(0, nonceLen);
    final largeShaRaw = [...utf8.encode(key), ...nonce];
    final largeShaRawMid = largeShaRaw.length ~/ 2;
    final msgKeyLarge = sha256.convert(largeShaRaw).bytes;
    final msgKey = msgKeyLarge.sublist(8, 24);

    final shaRawA = [...msgKey, ...largeShaRaw.sublist(0, largeShaRawMid)];
    final sha256a = sha256.convert(shaRawA).bytes;

    final shaRawB = [...largeShaRaw.sublist(largeShaRawMid), ...msgKey];
    final sha256b = sha256.convert(shaRawB).bytes;

    final aesKey = [...sha256a.sublist(0, 8), ...sha256b.sublist(8, 24), ...sha256a.sublist(24)];

    final aesIV = [...sha256b.sublist(0, 4), ...sha256a.sublist(12, 20), ...sha256b.sublist(28)];

    final encrypter = Encrypter(AES(Key(Uint8List.fromList(aesKey)), mode: AESMode.cbc));
    final decrypted = encrypter.decryptBytes(Encrypted(cipherBytes.sublist(nonceLen)), iv: IV(Uint8List.fromList(aesIV)));
    final text = const Utf8Decoder().convert(decrypted);
    return text;
  }
}
